package com.fh.utils;


import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.zip.CRC32;
@Component
public class BloomFilterUtils {
    /**
     * 构造函数：初始化布尔数组并赋值为false
     */
    private boolean[] bits = new boolean[10000]; // 存储所有槽位
    private final int[] SEEDS = new int[]{3, 7, 11, 13, 31, 37, 61};


    /**
     * 实现crc32哈希函数
     */
    public long crc32hash(String str, int seed){
        CRC32 crc32 = new CRC32();
        crc32.update(str.getBytes(StandardCharsets.UTF_8));
        return crc32.getValue() ^ seed;
    }

    /**
     * 将多个哈希值映射为位向量上的位置
     */
    public void add(String value) {
        for (int i = 0; i < SEEDS.length; i++) {
            long hash = crc32hash(value, SEEDS[i]);
            int bitIndex = (int) (hash % bits.length);
            bits[bitIndex] = true;
        }
    }

    /**
     * 检查某个元素是否在布隆过滤器中可能存在
     */
    public boolean contains(String value){
        boolean result = true;
        for (int i = 0; i < SEEDS.length && result; i++) {
            long hash = crc32hash(value, SEEDS[i]);
            int bitIndex = (int) (hash % bits.length);
            result = bits[bitIndex];
        }
        return result;
    }

    /**
     * 将字符串转换为哈希值数组
     */
    public long[] toHashArray(String value) {
        long[] hashes = new long[SEEDS.length];
        for (int i = 0; i < SEEDS.length; i++) {
            hashes[i] = crc32hash(value, SEEDS[i]);
        }
        return hashes;
    }

}